package com.example.demo.demos.redis.service;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class RedisService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    // 添加或更新排行榜中的用户分数
    public void updateLeaderboard(String leaderboardKey, String userId, double score) {
        redisTemplate.opsForZSet().add(leaderboardKey, userId, score);
    }

    // 获取排行榜前N名
    public Set<Object> getTopUsersFromLeaderboard(String leaderboardKey, long topN) {
        return redisTemplate.opsForZSet().reverseRange(leaderboardKey, 0, topN - 1);
    }

}